<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\controller\match;

use app\common\controller\BackendApi;
use app\common\manager\LogManager;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 赛事轮次成员管理
 *
 * @icon fa fa-circle-o
 */
class Roundmember extends BackendApi
{

    protected $color = [
        0=>['#E9544E','#E47470','#E68F8B'],
        1=>['#B668E9','#D1ABEA','#C389E9'],
        2=>['#E99B4F','#E8B889','#EAAC70'],
        3=>['#E8B74D','#E8CA8B','#E8BC5D'],
        4=>['#EBD759','#E7DA8B','#E8D871'],
        5=>['#D1EB59','#D8EA83','#D1E867'],
        6=>['#69D4EA','#99DEEC','#85DAEB'],
        7=>['#69EAD0','#ABEADD','#7AECD4'],
        8=>['#E97F4E','#EAA687','#EA9670'],
        9=>['#E471BD','#E9A6D2','#EA95CD']
    ];
    /**
     * Roundmember模型对象
     * @var \app\admin\model\match\Roundmember
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\match\Roundmember;
        $outList = $this->model->getOutList();
        $this->view->assign("outList", $outList);

    }


    /**
     * 查看
     */
    public function index()
    {
        $matchId = $this->request->param("ids");
        $mid = $this->request->request("mid");
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->alias('roundmember')
                    ->with(['match','round','member'])
                    ->where($where)
                    ->where(function ($query) use($mid){
                        if ($mid){
                            return $query->where('roundmember.match_id',$mid);
                        }
                    })
                    ->order('roundmember.round_id asc,roundmember.group_number asc,roundmember.group_inner_number asc')
                    ->paginate($limit);

            foreach ($list as &$row) {
                $mod = bcmod($row->group_number,10);
                $row->color = $this->color[$mod];
                //$this->color[bcmod($row->group_number,10)] = $row->color;
            }

            $result = array("total" => $list->total() , "rows" => $list->items() );

            return json($result);
        }
        $this->assign('matchId',$matchId);
        return $this->view->fetch();
    }

    public function add(){
        $startTime  = microtime(true);
        $matchId = $this->request->param("matchId");
        if (false === $this->request->isPost()) {
            $this->assign('matchId', $matchId);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if (\app\admin\model\match\Roundmember::where('match_id',$params['match_id'])->where('round_id',$params['round_id'])->where('member_id',$params['member_id'])->find()) {
                throw new Exception('同轮次同组内不能有相同成员存在');
            }
            if(empty($params['group_inner_number'])){
                $params['group_inner_number'] = 1;
            }
            $params['create_time'] = time();
            $params['update_time'] = time();
            $result = $this->model->allowField(true)->save($params);
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'添加赛事轮次小组成员',
                'data'=>$params,
                'match_id'=>$params['match_id'],
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $startTime = microtime(true);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['member_id'] != $row->member_id && \app\admin\model\match\Roundmember::where('match_id',$row->match_id)->where('round_id',$row->round_id)->where('member_id',$params['member_id'])->find()) {
                throw new Exception('同轮次同组内不能有相同成员存在');
            }
            $params['update_time'] = time();
            $totalScore = bcsub($params['score'],$row->score,2);
            if(!\app\admin\model\match\Member::where('id',$row->member_id)->setInc('score',$totalScore)){
                throw new Exception('成员积分修改失败，积分录入失败');
            }

            $result = $row->allowField(true)->save($params);
            if ($params['is_out'] == $this->model::IS_OUT){
                \app\admin\model\match\Member::where('id',$params['member_id'])->update([
                    'is_out'=>\app\admin\model\match\Member::IS_OUT,
                    'out_round'=>$row->round_id,
                    'update_time'=>time()
                ]);
            }
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'编辑赛事轮次小组成员',
                'data'=>$params,
                'match_id'=>$row->match_id,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('如若修改了当前轮次积分，请记得赛事结束后重新生成排行榜');
    }

    public function del($ids=null)
    {
        $startTime = microtime(true);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'删除赛事轮次小组成员',
                'data'=>$row,
                'match_id'=>$row->match_id,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
